package com.quotemanager.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.nirvana.core.Validator;
import com.quotemanager.exception.DataAccessException;
import com.quotemanager.exception.EmptyParamException;
import com.quotemanager.util.ConnectionFactory;

public class BrandDao {
	
	private static final String TABLE_NAME_BRAND = "BRAND";
	private static final String SEQ_NAME_BRAND = "SQ_BRAND";
	
	public boolean registerBrand(String brandName) throws DataAccessException{
		if(!Validator.isNullOrEmpty(brandName)){
			Connection connection = null;
			PreparedStatement statement = null;
			ResultSet result = null;
			try {
				String insertQuery = "INSERT INTO "+TABLE_NAME_BRAND+" VALUES(?,?)";
				String idQuery = "SELECT "+SEQ_NAME_BRAND+".NEXTVAL FROM DUAL";
				String brandId = "";
				boolean insertStatus = false;
				
				connection = ConnectionFactory.getConnection();
				statement = connection.prepareStatement(idQuery);
				result = statement.executeQuery();
				while(result.next()){
					brandId = result.getInt(1)+"";
					brandId = brandId.trim();
				}
				statement = connection.prepareStatement(insertQuery);
				statement.setString(1, brandId);
				statement.setString(2, brandName);
				int count = statement.executeUpdate();
				if(count > 0)
					insertStatus = true;
				else
					insertStatus = false;
				return insertStatus;
			} catch (SQLException e) {
				System.out.println("Exception in inserting Brand::");
				e.printStackTrace();
				throw new DataAccessException(e.getMessage(), e);
			}
			finally{
				ConnectionFactory.closeAll(connection, statement, result);
			}
		} else {
			throw new EmptyParamException("BrandName");
		} 
	}
}
